const mysql2 = require('mysql2');
const config = require('../config/database');
const getMysqlErrorMessageByErrno = require('../utils/DB');


class BaseModel {
  // db: db1, db2 默认db1
  constructor(db = 'db1') {
    const { host, user, password, database } = config[db];
    this.connectionDb(db);
  }

  connectionDb(db = 'db1') {
    const { host, user, password, database } = config[db];
    this.connection = mysql2.createConnection({
      host,
      user,
      password,
      database
    });
    this.connection.on('error', (err) => {
      console.log('db error', err);
      if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        console.log('db error执行重连:')
        this.connectionDb(db);
      } else {
        throw err;
      }
    });
  }

  getConn() {
    return this.connection;
  }

  query(sql, params) {
    return new Promise((resolve, reject) => {
      this.connection.query(sql, params, (err, results) => {
        if (err) {
          reject(err);
        } else {
          resolve(results);
        }
      })
    })
  }

  // 执行更新操作
  exec(sql, params) {
    return new Promise((resolve, reject) => {
      this.connection.execute(sql, params, (err, results) => {
        if (err) {
          reject(err);
        } else {
          resolve(results);
        }
      })
    })
  }

  exec2(sql) {
    return new Promise((resolve, reject) => {
      this.connection.query(sql, (err, results) => {
        if (err) {
          reject(err);
        } else {
          resolve(results);
        }
      })
    })
  }

  close() {
    this.connection.end();
  }

  getMysqlErrorMessageByErrno(errno) {
    return getMysqlErrorMessageByErrno(errno);
  }

  // 获取表所有字段
  async getTableFields(tableName) {
    try {
      const sql = `select column_name from information_schema.columns where table_schema = '${config.db1.database}' and table_name = '${tableName}'`;
      const results = await this.query(sql);
      return results.map(item => item.column_name);
    } catch (e) {
      console.log(e);
      return [];
    }
  }

  // buffer转换成base64图片
  bufferToBase64(buffer) {
    const blob = new Blob([buffer]);
    return blob;
  }
}


module.exports = BaseModel;